import time

from ttzScrapyProject.utils import HttpUtils
from ttzScrapyProject.utils import DateUtils
from ttzScrapyProject.utils import FileUtils
from ttzScrapyProject.utils import MumberUtils
from ttzScrapyProject.utils import ModelUtils

from ttzScrapyProject.dao import AccountLoginDao
from ttzScrapyProject.dao import LotteryInfoDao
from ttzScrapyProject.convert import parseLotteryInfoItem
from ttzScrapyProject.convert import parseModelInfoItem
from ttzScrapyProject.convert import parseUserItem
# from parseModelInfoItem import parseModelIndexData
from ttzScrapyProject.items import *
from decimal import Decimal, ROUND_HALF_UP


class TantanshuSpider(scrapy.Spider):
    name = 'tantanshu'
    allowed_domains = ['webapicname.coo456.com']
    start_urls = [
        # 用户登录页
        'http://webapicname.coo456.com/apiNew/H5login?token=3433a441ac7e0ea5f019f99f8e1600ad&client=app&Cellphone=17120572203&Password=qm1006406&Imei=unknow/',
        # 用户详情页
        "http://webapicname.coo456.com/apiNew/UserInfo?token=",
        # 当前最新一期正在开奖中的信息
        "http://webapicname.coo456.com/ApiNewLuck/lotteryInfo?token=",
        # 所有开奖信息首页
        "http://webapicname.coo456.com/ApiNewLuck/indexList?token=",
        # 当前期的赔率
        "http://webapicname.coo456.com/ApiNewLuck/modelIndex?token=",

        # 下注历史数据
        # "http://webapicname.coo456.com/ApiNewLuck/doingLottery?token=d3687d6809dd17db73f07730630666d7&g28=luck&arr=1,3,6,10,15,21,28,36,45,55,63,69,73,75,75,73,69,63,55,45,36,28,21,15,10,6,3,1&luckId=2695728"
        "http://webapicname.coo456.com/ApiNewLuck/myList?token=",

        # 上一期的下注及中奖明细
        # http://webapicname.coo456.com/ApiNewLuck/detail?token=5739c4dc41f44c712b645120dc00918e&g28=luck&luck28_id=2721358
        "http://webapicname.coo456.com/ApiNewLuck/detail?token=",

        # 下注
        # http://webapicname.coo456.com/ApiNewLuck/myList?token=5739c4dc41f44c712b645120dc00918e&g28=luck&Type=issue&PageNumber=1
        "http://webapicname.coo456.com/ApiNewLuck/doingLottery?token="

    ]

    ## 初始化当前轮数and 雪球索引
    currentSnowballParentIndex = 0
    currentSnowballChildrenIndex = 0
    # 爬虫启停标记
    stop = True
    """ 用户登录功能 ken=3433a441ac7e0ea5f019f99f8e1600ad&client=app HTTP/1.1
    """

    def __init__(self, userToken=None, userData=None, *args, **kwargs):
        super(TantanshuSpider, self).__init__(*args, **kwargs)
        self.userToken = userToken
        data = FileUtils.readUserLoginContext("userLoginInfo.txt")
        print(f"用户手机号为{data['phone']},用户密码为{data['password']}")
        # file.write(f"{item['Cellphone']},{item['Password']}\n")
        self.userPhone = data['phone']
        self.password = data['password']
        # 模式
        self.model = data['model']
        # 盈利目标
        self.winAmount = data['winAmount']
        # 亏损目标
        self.costAmount = data['costAmount']
        # 雪球轮数设置
        self.snowballCount = data['snowballCount']
        # 爬虫标识
        self.isScrpay = data['isScrpay']
        # 雪球目标设置
        self.snowballtarget = MumberUtils.strToInt(data['snowballtarget'])
        divisor = 100000
        result = Decimal(self.snowballtarget) / Decimal(divisor)
        result = result.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)  # 保留两位小数，四舍五入
        # 下注
        self.modelData = ModelUtils.getXZModelData(self.model[0:2], self.model, result)[
                         :MumberUtils.strToInt(self.snowballCount) + 1]
        # 滚雪球的次数
        self.modelSnowballCount = len(self.modelData)
        for i in self.modelData:
            # 滚雪球的轮数
            self.luckCount = len(i)
            break

    def parse(self, response):
        #         # {'Code': 200, 'Data': {'Token': 'fba01b8bab256b956b5784755314d0a5', 'UserId': '50720089', 'Pwd': '651ae74bce3802818455f5463cd2edd7', 'Cellphone': '17120572203'}}
        ## Debug 开始 ==============
        # loginData = AccountLoginDao.login(self, response)
        # if loginData == "":
        #     return;
        # self.userToken = loginData["Data"]["Token"]
        # self.userPhone = loginData["Data"]["Cellphone"]
        ## Debug 结束 ==============
        print(f"登录成功,用户Token为 {self.userToken}")

        userInfoUrl = self.start_urls[1] + self.userToken + "&client=app"
        # 将token 放入meta信息中

        print(userInfoUrl)
        meta_data = {"userToken": self.userToken, "userPhone": self.userPhone}
        yield scrapy.Request(url=userInfoUrl,
                             callback=self.parseUserInfo,
                             meta=meta_data
                             )

    """ 解析用户信息功能
    """

    def parseUserInfo(self, response):
        userInfo = AccountLoginDao.getUserInfo(self, response)
        userInfoData = userInfo['Data']
        userToken = response.meta["userToken"]
        userPhone = response.meta["userPhone"]
        # 用户id
        if userInfoData == "":
            return;
        userItem = parseUserItem.parseUserItemConvert(self, userInfoData)
        userItem["userToken"] = userToken
        userItem["userPhone"] = userPhone
        yield userItem

        print(f"用户信息为{userInfoData}")
        userId = userInfoData['UserId']
        # 银猪数量,用于下注
        coinBean = userInfoData['CoinBean']
        # doingLotteryInfoUrl = self.start_urls[2] + self.userToken + "&g28=luck"
        doingLotteryInfoUrl = f"{self.start_urls[2]}{self.userToken}&g28=luck"
        yield scrapy.Request(url=doingLotteryInfoUrl,
                             callback=self.parseDoingLotteryInfo,
                             meta=response.meta
                             )

    """ 
        解析当前正在开奖当前期的信息: 1条
    """

    def parseDoingLotteryInfo(self, response):
        doingLotteryInfoData = LotteryInfoDao.parseDoingLotteryInfo(self, response)
        if doingLotteryInfoData == "":
            return
        data = doingLotteryInfoData["Data"]

        print(f"当前正在开奖中的一期为{data}")
        # 期号当前期号
        lotteryIssue = data['LotteryIssue']
        # 最近一期的开奖信息
        lastLotteryIssue = data['Last']
        lotteryNum = data['LotteryNum']
        lotteryNum1 = data['LotteryNum1']
        lotteryNum2 = data['LotteryNum2']
        lotteryNum3 = data['LotteryNum3']
        countDownFuck = data['CountDownFuck']
        FileUtils.writeCountDownFuck("CountDownFuck.txt", countDownFuck)
        meta = response.meta
        userToken = meta["userToken"]
        # 期号
        meta = {"lotteryIssue": lotteryIssue, "userToken": userToken}
        indexUrl = self.start_urls[3] + self.userToken + "&g28=luck"

        if self.isScrpay == 'True':
            # 数据爬虫,解析半小时内的20条数据======== start
            yield scrapy.Request(url=indexUrl, callback=self.parseIndexData, meta=meta)
        elif self.isScrpay == 'False':
            # 自动下注
            # 当天的下注历史
            # http://webapicname.coo456.com/ApiNewLuck/myList?token=1a69c964530a06748b953bd06695d3fb&g28=luck&Type=issue&PageNumber=1
            lastTransactionUrl = f"{self.start_urls[5]}{self.userToken}&g28=luck&Type=issue&PageNumber=1"
            yield scrapy.Request(url=lastTransactionUrl, callback=self.parseLastTransactionInfoList, meta=meta)

    def convertDoneLotterInfoItemList(self, data):
        lotterInfoItemList = []
        item = {}
        lotterInfoItemList.append(item)
        item['Id'] = data['LotteryIssue']
        # 最近一期的开奖信息
        lastLotteryIssue = data['Last']

        # lotteryNum = data['LotteryNum']
        # lotteryNum1 = data['LotteryNum1']
        # lotteryNum2 = data['LotteryNum2']
        # lotteryNum3 = data['LotteryNum3']
        item['LuckNum'] = data['LotteryNum']
        item['Num1'] = data['LotteryNum1']
        item['Num2'] = data['LotteryNum2']
        item['Num3'] = data['LotteryNum3']
        item['LuckNumRate'] = 9999
        item['LotteryTime'] = time.time()
        item['UpdateTime'] = time.time()
        item['TotalSum'] = 99999999999999

        return lotterInfoItemList

    """
        解析首页已开奖信息,15条
    """

    def parseIndexData(self, response):
        indexData = LotteryInfoDao.parseIndexDataInfo(self, response)
        print(f"全部的首页数据为{indexData}")
        # 赔率数据
        doingData = indexData["Data"]["DoingLuckList"]
        # 已经开奖的历史数据
        data = indexData["Data"]["DoneLuckList"]
        lotteryInfoList = parseLotteryInfoItem.parseLotteryInfo(self, data)
        for lotteryInfo in lotteryInfoList:
            yield lotteryInfo
        lotteryDoingInfo = parseLotteryInfoItem.parseDoingLotteryInfoItem(self, doingData)
        # yield lotteryDoingInfo
        metaInfo = response.meta
        userToken = metaInfo["userToken"]
        lotteryIssue = metaInfo["lotteryIssue"]
        metaInfo["lotteryDoingInfo"] = lotteryDoingInfo
        metaInfo["lotteryInfo"] = lotteryInfoList[0]
        # modelIndexUrl = self.start_urls[4] + self.userToken + "&g28=luck&Luck28Id=" + lotteryIssue
        modelIndexUrl = f"{self.start_urls[4]}{self.userToken}&g28=luck&Luck28Id={lotteryIssue}"
        print(f"modelIndexUrl={modelIndexUrl}")
        yield scrapy.Request(url=modelIndexUrl, callback=self.modelIndexData, meta=metaInfo)
        # 获取当前期每个号码的赔率信息
        # "http://webapicname.coo456.com/ApiNewLuck/modelIndex?token=4d222239b4267a2b90ec6ec157ee0a28&g28=luck&Luck28Id=2694748"

    """
        解析赔率并获取要下注的账号
    """

    def modelIndexData(self, response):
        data = LotteryInfoDao.parseIndexDataInfo(self, response)
        modelData = parseModelInfoItem.parseModelIndexData(self, data)
        lotteryDoingInfo = response.meta["lotteryDoingInfo"]
        lotteryInfo = response.meta["lotteryInfo"]
        modelStr = ""
        for key in lotteryDoingInfo.keys():
            tempSum = float(lotteryDoingInfo[key]) * float(modelData[key])
            totalSum = lotteryInfo["totalSum"]
            booleanCompare = MumberUtils.compare(float(tempSum), float(totalSum))
            print(f"{key}的中奖后奖池{tempSum},总奖池为{totalSum},满足下注条件{booleanCompare}")

            if booleanCompare:
                modelStr = modelStr + str(MumberUtils.getBettingAmount(key)) + ","
            else:
                modelStr = modelStr + "0,"
        print(f"赔率信息为{modelData}下注信息为{modelStr}")
        yield modelData

    """
        =========== 自动爬虫的代码已经够用的====================end
    """

    """
        自动下注代码
    
    """

    """
        解析交易信息
    """

    def parseTransactionInfo(self, response):
        # {"Code":200,"Msg":"参与成功"}
        data = HttpUtils.parseResponseData(self, response)
        if data == "":
            return;

        if data["Msg"] == "参与成功":
            print("下注成功")
        print("下注完成,检查")

    """
     解析上一期的交易信息
    """

    def parseLastTransactionInfoList(self, response):
        data = HttpUtils.parseResponseData(self, response)
        if data == "":
            print("检查到上一期没有下注")
        # {"Code":200,"Data":{"TodayWin":"-104","TodayWinRate":0.09,"YesterdayWin":"-630","MonthWin":"-18781930","ChartData":["75.86","76.60","100.00","71.43","83.81","2.04","8.57"],"List":{"TotalCount":387,"PageCount":26,"PageNumber":"1","PageSize":"15","Rows":[{"Id":"2722531","UserId":"50720089","UserType":"normal","LuckNum":"14","CostSum":"1000","WinSum":"999","DateStr":"20231217","CreateTime":"1702805888","Num1":"3","Num2":"2","Num3":"9"},{"Id":"2722530","UserId":"50720089","UserType":"normal","LuckNum":"17","CostSum":"1000","WinSum":"999","DateStr":"20231217","CreateTime":"1702805798","Num1":"1","Num2":"9","Num3":"7"},{"Id":"2722529","UserId":"50720089","UserType":"normal","LuckNum":"10","CostSum":"1000","WinSum":"999","DateStr":"20231217","CreateTime":"1702805708","Num1":"4","Num2":"1","Num3":"5"},{"Id":"2722528","UserId":"50720089","UserType":"normal","LuckNum":"14","CostSum":"1000","WinSum":"999","DateStr":"20231217","CreateTime":"1702805618","Num1":"1","Num2":"7","Num3":"6"},{"Id":"2722527","UserId":"50720089","UserType":"normal","LuckNum":"7","CostSum":"1000","WinSum":"998","DateStr":"20231217","CreateTime":"1702805528","Num1":"1","Num2":"0","Num3":"6"},{"Id":"2722526","UserId":"50720089","UserType":"normal","LuckNum":"13","CostSum":"1000","WinSum":"999","DateStr":"20231217","CreateTime":"1702805439","Num1":"9","Num2":"4","Num3":"0"},{"Id":"2722525","UserId":"50720089","UserType":"normal","LuckNum":"15","CostSum":"1000","WinSum":"999","DateStr":"20231217","CreateTime":"1702805348","Num1":"4","Num2":"3","Num3":"8"},{"Id":"2722524","UserId":"50720089","UserType":"normal","LuckNum":"18","CostSum":"1000","WinSum":"999","DateStr":"20231217","CreateTime":"1702805258","Num1":"4","Num2":"7","Num3":"7"},{"Id":"2722523","UserId":"50720089","UserType":"normal","LuckNum":"13","CostSum":"1000","WinSum":"999","DateStr":"20231217","CreateTime":"1702805169","Num1":"8","Num2":"3","Num3":"2"},{"Id":"2722522","UserId":"50720089","UserType":"normal","LuckNum":"15","CostSum":"1000","WinSum":"998","DateStr":"20231217","CreateTime":"1702805079","Num1":"8","Num2":"2","Num3":"5"},{"Id":"2722513","UserId":"50720089","UserType":"normal","LuckNum":"13","CostSum":"1000","WinSum":"998","DateStr":"20231217","CreateTime":"1702804269","Num1":"2","Num2":"3","Num3":"8"},{"Id":"2722508","UserId":"50720089","UserType":"normal","LuckNum":"12","CostSum":"1000","WinSum":"998","DateStr":"20231217","CreateTime":"1702803827","Num1":"6","Num2":"3","Num3":"3"},{"Id":"2722491","UserId":"50720089","UserType":"normal","LuckNum":"20","CostSum":"1000","WinSum":"997","DateStr":"20231217","CreateTime":"1702802290","Num1":"6","Num2":"7","Num3":"7"},{"Id":"2722485","UserId":"50720089","UserType":"normal","LuckNum":"18","CostSum":"1000","WinSum":"997","DateStr":"20231217","CreateTime":"1702801765","Num1":"7","Num2":"9","Num3":"2"},{"Id":"2722483","UserId":"50720089","UserType":"normal","LuckNum":"14","CostSum":"1000","WinSum":"999","DateStr":"20231217","CreateTime":"1702801569","Num1":"0","Num2":"8","Num3":"6"}]}}}
        detailData = data["Data"]
        content = ""

        # 今日盈亏
        TodayWin = MumberUtils.strToInt(detailData["TodayWin"])
        if TodayWin > MumberUtils.strToInt(self.winAmount):
            item = {
                "currentSnowballParentIndex": 0,
                "currentSnowballChildrenIndex": 0
            }
            FileUtils.writeSnowballData("SnowballData.txt", item)
            self.stop = False

        # 亏损判断
        if abs(TodayWin) > MumberUtils.strToInt(self.costAmount):
            item = {
                "currentSnowballParentIndex": 0,
                "currentSnowballChildrenIndex": 0
            }
            FileUtils.writeSnowballData("SnowballData.txt", item)
            self.stop = False

        #     return "目标未到达"

        # 左闭右开
        dataList = detailData["List"]["Rows"][0:1]
        for index, item in enumerate(dataList):
            #  期号
            detailDataId = item["Id"]
            # 号码
            LuckNum = item["LuckNum"]
            Num1 = item["Num1"]
            Num2 = item["Num2"]
            Num3 = item["Num3"]
            # 下注
            CostSum = item["CostSum"]
            # 盈利额
            WinSum = item["WinSum"]
            # 下注时间
            CreateTime = item["CreateTime"]
            # 亏损
            diff = MumberUtils.strToInt(WinSum) - MumberUtils.strToInt(CostSum)

            if self.stop:
                tempData = FileUtils.readSnowballData("SnowballData.txt")
                if tempData != "":
                    self.currentSnowballParentIndex = MumberUtils.strToInt(tempData["currentSnowballParentIndex"])
                    self.currentSnowballChildrenIndex = MumberUtils.strToInt(tempData["currentSnowballChildrenIndex"])
                if diff > 0:
                    self.currentSnowballChildrenIndex = self.currentSnowballChildrenIndex + 1
                    # 大于轮数 则进行回滚,表明此轮全中
                    if MumberUtils.strToInt(self.currentSnowballChildrenIndex) >= MumberUtils.strToInt(self.luckCount):
                        self.currentSnowballChildrenIndex = 0
                        self.currentSnowballParentIndex = 0
                else:
                    # 小于雪球轮数 则进行下一期推雪球模式
                    if MumberUtils.strToInt(self.currentSnowballChildrenIndex) > MumberUtils.strToInt(
                            self.snowballCount):
                        self.currentSnowballChildrenIndex = 0
                        self.currentSnowballParentIndex = 0
                    else:
                        self.currentSnowballParentIndex = self.currentSnowballParentIndex + 1
                        self.currentSnowballChildrenIndex = 0

            content = content + f"{detailDataId},{Num1},{Num2},{Num3},{LuckNum},99999999999,9999,{DateUtils.timestamp2Date(MumberUtils.strToInt(CreateTime))},{CostSum},是,{WinSum}\n"
        FileUtils.writeCountDownFuck("lotterInfoItem.txt", content)

        # 当前期号的交易信息 如果没有到达 亏损 or 盈利目标就下注
        if self.stop:
            print(f"当前轮数{self.currentSnowballParentIndex},第{self.currentSnowballChildrenIndex}轮")
            if MumberUtils.strToInt(self.currentSnowballParentIndex) >= MumberUtils.strToInt(self.snowballCount):
                self.currentSnowballParentIndex = 0
            item = {
                "currentSnowballParentIndex": self.currentSnowballParentIndex,
                "currentSnowballChildrenIndex": self.currentSnowballChildrenIndex
            }
            FileUtils.writeSnowballData("SnowballData.txt", item)

            # 开始下注
            metaInfo = response.meta
            lotteryIssue = metaInfo["lotteryIssue"]

            arr = self.modelData[self.currentSnowballParentIndex][self.currentSnowballChildrenIndex]
            transactionUrl = f"{self.start_urls[7]}{self.userToken}&g28=luck&arr={arr}&luckId={lotteryIssue}"
            yield scrapy.Request(url=transactionUrl, callback=self.parseTransactionInfo, meta=data)
